const express = require('express')

const Joi = require('joi')

const todo = express.Router()

const Todotask = require('../model/todoTask')

todo.get('/', (req, res) => {
    res.render('index')
})

// 展示任务
todo.get('/task', async (req, res) => {
    let tasks = await Todotask.find()
    res.send(tasks)
})

// 删除任务
todo.get('/deleteTask', async (req, res) => {
    let {
        _id
    } = req.query

    let deleteOne = await Todotask.findOneAndDelete({
        _id
    })

    res.send(deleteOne)
})

// 添加任务
todo.post('/addTask', async (req, res) => {
    let {
        title
    } = req.body

    let schema = Joi.object({
        title: Joi.string().required().min(2).max(30).error(new Error('任务名称长度不相符'))
    })

    const {
        error,
        value
    } = schema.validate(req.body);

    if (error) {
        return res.status(400).send({
            message: error.message
        })
    }

    let taskCreate = await Todotask.create({
        title
    })
    setTimeout(() => {
        res.send(taskCreate)
    }, 2000)

})

// 更改任务状态
todo.post('/todo/modifyTask', async (req, res) => {
    let {
        _id,
        completed,
        title
    } = req.body
    let updateOne = await Todotask.findOneAndUpdate({
        _id
    }, {
        completed,
        title
    }, {
        new: true
    })
    res.send(updateOne)
})

// 清除已完成任务
todo.get('/todo/clearCompleted', async (req, res) => {
    await Todotask.deleteMany({
        completed: true
    })
    let tasks = await Todotask.find()
    res.send(tasks)
})

module.exports = todo